import { releaseInterview, treeReleaseAssignContact } from '@/services/api/api-needs';
import { CheckCircleTwoTone, SendOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProFormInstance,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Alert, Button, Divider, message, Space, Spin, Tag } from 'antd';
import Tree, { DataNode } from 'antd/es/tree';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';

interface AddReleaseProps {
  interviewId: string;
  onRefurbish: () => void;
}

const AddRelease: React.FC<AddReleaseProps> = ({ interviewId, onRefurbish }) => {
  const access = useAccess();
  const { initialState, setInitialState } = useModel('@@initialState');

  const [loading, setLoading] = useState(false);

  const formRef = useRef<ProFormInstance>();

  const [openAddActive, setOpenAddActive] = useState<boolean>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const [dataTreeAddress, setDataTreeAddressState] = useState<DataNode[]>();

  const [assignCombineIds, setAssignCombineIdsState] = useState<string[]>();

  /**
   * 加载组织树请求网络
   */
  const loadAddressTreeData = async () => {
    try {
      setLoading(true);

      const response = await treeReleaseAssignContact({
        id: interviewId,
      });
      console.log(readyTreeAddressData(response.data));

      if (response.code === 0) {
        setDataTreeAddressState(readyTreeAddressData(response.data));
      }

      setLoading(false);
    } catch (error) {}
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeAddressData(data: Array<UserData.Organization>): any {
    const treeData = new Array();
    console.log(data);

    if (data) {
      data.forEach((val, idx, array) => {
        treeData.push({
          title: (
            <>
              <span>{val.name}</span>
              {val?.marks && val?.marks.length > 0 && (
                <>
                  <Space wrap>
                    {val?.marks.map((item) => (
                      <Tag bordered={false} color="orange">
                        {item}
                      </Tag>
                    ))}
                  </Space>
                </>
              )}
            </>
          ),
          key: val.id,
          isCombine: val.isCombine,
          children: readyTreeAddressData(val.children as Array<UserData.Organization>),
        });
      });
    }
    return treeData;
  }

  return (
    <DrawerForm
      key="drawer_form_add_release"
      title="发布"
      drawerProps={{
        destroyOnClose: true,
        width: 800,
        maskClosable: false,
      }}
      formRef={formRef}
      trigger={
        <Button
          key="button_add_release"
          icon={<SendOutlined />}
          type="primary"
          style={{
            background: '#87d068',
          }}
        >
          发布
        </Button>
      }
      initialValues={{
        initiateOrganization: initialState?.currentUser?.organizationName,
      }}
      open={openAddActive}
      onOpenChange={(visible) => {
        if (visible) {
          loadAddressTreeData();
        } else {
          setAssignCombineIdsState([]);
        }
        setOpenAddActive(visible);
      }}
      layout="horizontal"
      submitter={{
        render: (props, defaultDoms) => {
          return [
            <Button onClick={() => setOpenAddActive(false)}>取消</Button>,
            <Button
              key="button_add_submit"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                setModalFormOpenState(true);
              }}
            >
              发布
            </Button>,
            <ModalForm
              key={'modal_form_add_submit'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  发布
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                const values = formRef.current?.getFieldsValue();

                const response = await releaseInterview({
                  ...values,
                  id: interviewId,
                  assignCombineIds: assignCombineIds,
                });

                if (response.code === 0) {
                  message.success('提交成功');
                  setOpenAddActive(false);
                  onRefurbish();
                  return true;
                } else {
                  return false;
                }
              }}
            />,
          ];
        },
      }}
    >
      <ProFormTextArea
        width="xl"
        name="releaseContent"
        label="审批意见"
        fieldProps={{
          allowClear: true,
          maxLength: 600,
        }}
      />
      <Spin spinning={loading}>
        {dataTreeAddress && (
          <>
            <Divider
              orientation="left"
              style={{
                fontSize: 14,
                fontWeight: 'bold',
              }}
            >
              设置浏览权限
            </Divider>
            <Alert message="如不选择，默认推送所有人" type="warning" />
            <Tree
              style={{
                marginTop: '16px',
              }}
              treeData={dataTreeAddress}
              defaultExpandAll
              checkable
              selectable={false}
              onCheck={(checkedKeys, e) => {
                const checkKeys = new Array();

                e.checkedNodesPositions?.map((item) => {
                  if (item.node.isCombine == 1) {
                    checkKeys.push(item.node.key);
                  }
                });

                setAssignCombineIdsState(checkKeys);
              }}
            />
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default AddRelease;
